package com.chinaums.study.restful.service;

import com.jcraft.jsch.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Properties;

@Service
public class SftpService {

    private Session session;

    @PostConstruct
    private void init() throws JSchException {
        final JSch jsch = new JSch(); // 创建JSch对象
        session = jsch.getSession("photo", "172.16.208.86", 22);
        session.setPassword("photo@2017");

        final Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // 为Session对象设置properties
        session.setTimeout(10000); // 设置timeout时间
        session.connect(); // 通过Session建立链接
    }

    @PreDestroy
    private void destroy() {
        session.disconnect();
    }

    public String upload(final byte[] bytes) throws JSchException, SftpException, IOException {
        if (!session.isConnected()) {
            session.connect();
        }
        final String fileName = "/photo/" + DigestUtils.md5Hex(bytes) + ".jpg";
        final ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); // 打开SFTP通道
        channel.connect(); // 建立SFTP通道的连接
        channel.put(new ByteArrayInputStream(bytes), fileName);
        channel.disconnect();
        return fileName;
    }

    public void delete(final String fileName) throws JSchException, SftpException {
        if (!session.isConnected()) {
            session.connect();
        }
        final ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); // 打开SFTP通道
        channel.connect(); // 建立SFTP通道的连接
        channel.rm(fileName);
        channel.disconnect();
    }
}
